import { useEffect, useState } from "react";
import { NameId, fetchData } from "../api";

type Returned = [NameId[], string, React.Dispatch<React.SetStateAction<string>>];
function useSelectOptions(url?: string): Returned {
  const [list, setList] = useState<NameId[]>([]);
  const [id, setId] = useState("");

  useEffect(() => {
    if (url === undefined) {
      return;
    }

    let ignore = false;
    fetchData(url).then(result => {
      if (!ignore) {
        setList(result);
        setId(result[0].id);
      }
    });

    return () => {
      ignore = true;
    };
  }, [url]);

  return [list, id, setId];
}

export default useSelectOptions;
